package cn.itcast.netty.c2;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.ReferenceCountUtil;

import java.nio.charset.Charset;
import java.util.Scanner;

public class EchoClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Channel channel = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringEncoder(Charset.defaultCharset()));
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    try {
                                        ByteBuf buffer = (ByteBuf) msg;
                                        System.out.println("Client received: " + buffer.toString(Charset.defaultCharset()));

                                        // 注意：这里不需要手动释放buffer，因为Netty会在pipeline处理完成后自动释放
                                    } finally {
                                        ReferenceCountUtil.release(msg);  // 更安全的做法
                                    }
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                    cause.printStackTrace();
                                    ctx.close();
                                }
                            });
                        }
                    }).connect("localhost", 8080).sync().channel();

            channel.closeFuture().addListener(future -> {
                group.shutdownGracefully();  // 优雅关闭
            });

            Scanner sc = new Scanner(System.in);
            while (true) {
                String line = sc.nextLine();
                if("q".equals(line)) {
                    channel.close();
                    break;
                }
                channel.writeAndFlush(line);
            }
        } finally {
            group.shutdownGracefully();  // 优雅关闭
        }
    }
}
